// app/(tabs)/history.js
import Loading from '@/components/Loading';
import { api } from '@/utils/request/Api';
import { Ionicons } from '@expo/vector-icons';
import { router } from 'expo-router';
import { History } from '@/interface/interface';
import React, { useEffect, useState } from 'react';
import { Alert, FlatList,RefreshControl, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
let page = 1;
export default function HistoryScreen() {
    const [loading, setLoading] = useState(false);
    const [historys, setHistorys] = useState<History[]>([]);
    const [lastpage,setLastpage] = useState(1);
    //const [page, setPage] = useState(1);
    const [refreshing, setRefreshing] = useState(false);
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await api.get('crawl/history', { params: { page: page } });
        if(page === 1){
          setHistorys(response.data.data);
        }else{
          setHistorys(prev => [...prev, ...(response.data.data as History[])]);
        }
        setLastpage(response.data.last_page);
      } catch (err) {
        console.error('Error fetching data:', err);
      } finally {
        if(refreshing){
          setRefreshing(false)
        }
        setLoading(false);
      }
    };
    const handleLoadMore = () => {
      if(page > 0 && page < lastpage){
        page++;
        fetchData();
      }
    }
    const onDelete = async (id: number)  => {
      Alert.alert("warning","Are you sure you want to delete this item?",[
        {
          text: "Cancel",
          onPress: () => {},
          style: "cancel"
        },
        { text: "OK", onPress: async () => {
            try {
              setLoading(true);
              const response = await api.get('crawl/delete', { params: { id: id } });
              if(response.code == 0){
                  Alert.alert("Tip","Delete Failed");
              }else{
                const items = historys.filter((item) => item.id != id);
                setHistorys(items);
              }
            } catch (err) {
              Alert.alert("Tip","Delete Failed");
            }finally {
              setLoading(false);
            }
        }}
      ]);
      console.log(id)
    }
    useEffect(() => {
      fetchData();
    }, []);
    const onRefresh = () => {
      setLastpage(1);
      page = 1;
      //setRefreshing(true);
      setHistorys([])
      handleLoadMore();
    }
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>Crawl History</Text>
        <TouchableOpacity>
          <Ionicons name="trash-outline" size={22} color="#f43f5e" />
        </TouchableOpacity>
      </View>

      <FlatList
        data={historys}
        onEndReached={handleLoadMore}
        onEndReachedThreshold={10}
        keyExtractor={(item: History) => item.id?.toString() || Math.random().toString(36).substr(2, 9)}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => onRefresh()}/>}
        renderItem={({ item }) => (
          <View style={styles.card}>
            <View style={styles.row}>
              <Text style={styles.url}>{item.url}</Text>
              <TouchableOpacity>
                <Ionicons name="open-outline"  onPress={()=>router.push(`/emails?crawlId=${item.id}`)} size={18} color="#333" />
              </TouchableOpacity>
              <TouchableOpacity style={{ marginLeft: 12 }}>
                <Ionicons name="trash" size={18} color="#f43f5e" onPress={()=>item.id && onDelete(item.id)}/>
              </TouchableOpacity>
            </View>
            <View style={styles.detail}>
              <Text style={styles.meta}><Text style={styles.label}>Date:</Text> {item.created_at}</Text>
              <Text style={styles.meta}><Text style={styles.label}>Emails found:</Text> {item.email_count}</Text>
              <Text style={styles.meta}><Text style={styles.label}>Pages crawled:</Text> {item.pages}</Text>
            </View>
          </View>
        )}
      />
      {loading && <Loading />}
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 15, backgroundColor: '#fff' },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  title: { fontSize: 22, fontWeight: '600' },
  card: {
    backgroundColor: '#f9fafb', marginTop: 16, padding: 16, borderRadius: 12
  },
  row: {
    flexDirection: 'row', alignItems: 'center', marginBottom: 12
  },
  url: { fontWeight: '600', flex: 1 },
  detail: { gap: 4 },
  label: { fontWeight: '600', color: '#444' },
  meta: { fontSize: 14, color: '#333' },
});
